package client;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class SystemProperties extends Properties {

	// the variable
	private final static String SERVER_IP_KEY = "server_ip_address";
	private final static String SERVER_IP_DEFAULT = "127.0.0.1";

	private final static String SERVER_PORT_KEY = "server_port";
	private final static String SERVER_PORT_DEFAULT = "81";

	private static final String DEFAULT_CONFIG_LOCATION = "src/client/Config.Properties";
	private static SystemProperties instance; // Singleton instance

	// sets the ip adress in the config file
	public static void setServerIp(String value) {
		getInstance().setProperty(SERVER_IP_KEY, value);
		try {
			getInstance().store(new FileOutputStream(DEFAULT_CONFIG_LOCATION),
					null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// sets the port in the config file
	public static void setServerPort(String values) {
		getInstance().setProperty(SERVER_PORT_KEY, values);
		try {
			getInstance().store(new FileOutputStream(DEFAULT_CONFIG_LOCATION),
					null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// gets the ip adress in the config file
	public static String getServerIp() {
		getInstance().loadFromDefaultLocation();
		return getInstance().getProperty(SERVER_IP_KEY, SERVER_IP_DEFAULT);
	}

	// gets the port in the config file
	public static String getServerPort() {
		getInstance().loadFromDefaultLocation();
		return getInstance().getProperty(SERVER_PORT_KEY, SERVER_PORT_DEFAULT);
	}

	// load the config file
	private SystemProperties loadFromDefaultLocation() {
		try {
			load(new FileInputStream(DEFAULT_CONFIG_LOCATION));
		} catch (FileNotFoundException e) {
			System.out
					.println("Could not find config file, using default values.");
			e.printStackTrace();
		} catch (IOException e) {
			System.out
					.println("Could not load config file, using default values.");
			e.printStackTrace();
		}
		return this;
	}

	private static SystemProperties getInstance() {
		if (instance == null) {
			instance = new SystemProperties().loadFromDefaultLocation();
		}
		return instance;
	}
}